package com.example.managemyself.util;

import android.content.Context;
import android.util.Log;

import com.example.managemyself.data.database.AppDatabase;
import com.example.managemyself.data.model.DiaryEntry;
import com.example.managemyself.data.model.Task;
import com.example.managemyself.data.model.User;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * AI贴身助手管理器
 * 为AI提供用户的完整上下文信息，包括日记、任务等
 */
public class PersonalAIAssistant {
    
    private static final String TAG = "PersonalAIAssistant";
    
    private static PersonalAIAssistant instance;
    private final AppDatabase database;
    private final UserManager userManager;
    private final ExecutorService executorService;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());
    
    private PersonalAIAssistant(Context context) {
        database = AppDatabase.getInstance(context);
        userManager = UserManager.getInstance();
        executorService = Executors.newSingleThreadExecutor();
    }
    
    public static synchronized PersonalAIAssistant getInstance(Context context) {
        if (instance == null) {
            instance = new PersonalAIAssistant(context.getApplicationContext());
        }
        return instance;
    }
    
    /**
     * 为AI对话增强上下文
     */
    public void enhanceAIMessage(String userMessage, EnhancedMessageCallback callback) {
        String lowerMessage = userMessage.toLowerCase();
        
        if (containsPersonalQuery(lowerMessage)) {
            generateUserContext(context -> {
                String enhancedMessage = "【系统提示】你是用户的贴身AI助手，请基于以下用户信息回答问题：\n\n" +
                                       context + "\n\n" +
                                       "【用户问题】" + userMessage + "\n\n" +
                                       "【回答要求】请用亲切、个性化的语调回答，体现出你对用户情况的了解。";
                callback.onResult(enhancedMessage);
            });
        } else {
            User currentUser = userManager.getCurrentUser();
            if (currentUser != null) {
                String enhancedMessage = "【系统提示】你是" + currentUser.getDisplayName() + "的贴身AI助手，请用亲切、个性化的语调回答。\n\n" +
                                       "【用户问题】" + userMessage;
                callback.onResult(enhancedMessage);
            } else {
                callback.onResult(userMessage);
            }
        }
    }
    
    /**
     * 生成用户上下文信息
     */
    public void generateUserContext(UserContextCallback callback) {
        executorService.execute(() -> {
            try {
                User currentUser = userManager.getCurrentUser();
                if (currentUser == null) {
                    callback.onResult("用户未登录，无法获取个人信息");
                    return;
                }
                
                StringBuilder context = new StringBuilder();
                
                // 基本用户信息
                context.append("=== 用户基本信息 ===\n");
                context.append("用户名：").append(currentUser.getDisplayName()).append("\n");
                context.append("注册时间：").append(formatDate(currentUser.getCreatedDate())).append("\n\n");
                
                // 获取最近的日记信息
                appendRecentDiaries(context);
                
                // 获取任务信息
                appendTasksInfo(context);
                
                callback.onResult(context.toString());
                
            } catch (Exception e) {
                Log.e(TAG, "生成用户上下文失败", e);
                callback.onResult("获取用户信息时出现错误");
            }
        });
    }
    
    /**
     * 搜索用户的历史记录
     */
    public void searchUserHistory(String keyword, HistorySearchCallback callback) {
        executorService.execute(() -> {
            try {
                User currentUser = userManager.getCurrentUser();
                if (currentUser == null) {
                    callback.onResult("用户未登录，无法搜索历史记录");
                    return;
                }
                
                StringBuilder result = new StringBuilder();
                result.append("=== 搜索结果：").append(keyword).append(" ===\n");
                
                // 搜索日记
                List<DiaryEntry> diaryResults = database.diaryEntryDao().searchDiariesSync("%" + keyword + "%");
                if (!diaryResults.isEmpty()) {
                    result.append("\n📝 相关日记（").append(diaryResults.size()).append("条）：\n");
                    for (DiaryEntry diary : diaryResults) {
                        result.append("• ").append(formatDate(diary.getDate())).append("：")
                              .append(diary.getTitle()).append("\n");
                        if (diary.getContent() != null && diary.getContent().contains(keyword)) {
                            // 提取包含关键词的片段
                            String[] sentences = diary.getContent().split("[。！？\\n]");
                            for (String sentence : sentences) {
                                if (sentence.contains(keyword)) {
                                    result.append("  \"").append(sentence.trim()).append("\"\n");
                                    break;
                                }
                            }
                        }
                    }
                }
                
                // 搜索任务
                List<Task> taskResults = database.taskDao().searchTasksSync("%" + keyword + "%");
                if (!taskResults.isEmpty()) {
                    result.append("\n✅ 相关任务（").append(taskResults.size()).append("个）：\n");
                    for (Task task : taskResults) {
                        result.append("• ").append(task.getTitle())
                              .append("（").append(task.getType()).append("）")
                              .append(task.isCompleted() ? " ✓" : " ○").append("\n");
                    }
                }
                
                if (diaryResults.isEmpty() && taskResults.isEmpty()) {
                    result.append("\n未找到包含\"").append(keyword).append("\"的相关记录。");
                }
                
                callback.onResult(result.toString());
                
            } catch (Exception e) {
                Log.e(TAG, "搜索历史记录失败", e);
                callback.onResult("搜索历史记录时出现错误");
            }
        });
    }
    
    private void appendRecentDiaries(StringBuilder context) {
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DAY_OF_YEAR, -7); // 最近7天
            Date weekAgo = calendar.getTime();
            
            List<DiaryEntry> recentDiaries = database.diaryEntryDao().getDiariesAfterDateSync(weekAgo);
            
            context.append("=== 最近7天日记记录 ===\n");
            if (recentDiaries.isEmpty()) {
                context.append("最近没有写日记\n\n");
            } else {
                for (DiaryEntry diary : recentDiaries) {
                    context.append(formatDate(diary.getDate())).append("：").append(diary.getTitle()).append("\n");
                    if (diary.getContent() != null && diary.getContent().length() > 100) {
                        context.append("内容摘要：").append(diary.getContent().substring(0, 100)).append("...\n");
                    } else if (diary.getContent() != null) {
                        context.append("内容：").append(diary.getContent()).append("\n");
                    }
                }
                context.append("\n");
            }
        } catch (Exception e) {
            Log.e(TAG, "获取最近日记失败", e);
        }
    }
    
    private void appendTasksInfo(StringBuilder context) {
        try {
            List<Task> allTasks = database.taskDao().getAllTasksSync();
            List<Task> pendingTasks = database.taskDao().getPendingTasksSync();
            
            context.append("=== 任务情况 ===\n");
            context.append("总任务数：").append(allTasks.size()).append("\n");
            context.append("待完成任务：").append(pendingTasks.size()).append("\n");
            
            if (!pendingTasks.isEmpty()) {
                context.append("近期待办：\n");
                for (int i = 0; i < Math.min(5, pendingTasks.size()); i++) {
                    Task task = pendingTasks.get(i);
                    context.append("• ").append(task.getTitle()).append("（").append(task.getType()).append("）\n");
                }
            }
            context.append("\n");
        } catch (Exception e) {
            Log.e(TAG, "获取任务信息失败", e);
        }
    }
    
    private boolean containsPersonalQuery(String message) {
        String[] personalKeywords = {
            "我", "我的", "日记", "任务", "做了什么", "写了什么", "最近", "这几天", 
            "昨天", "前天", "上周", "完成", "记录", "活动", "情况", "今天做了", "写过什么"
        };
        
        for (String keyword : personalKeywords) {
            if (message.contains(keyword)) {
                return true;
            }
        }
        return false;
    }
    
    private String formatDate(Date date) {
        if (date == null) return "未知日期";
        return dateFormat.format(date);
    }
    
    // 回调接口
    public interface UserContextCallback {
        void onResult(String context);
    }
    
    public interface HistorySearchCallback {
        void onResult(String result);
    }
    
    public interface EnhancedMessageCallback {
        void onResult(String enhancedMessage);
    }
} 